package com.pxx.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxx.common.utils.R;
import com.pxx.item.mapper.TbCategoryMapper;
import com.pxx.item.pojo.TbCategory;
import com.pxx.item.service.TbCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
* @author Yoo19
* @description 针对表【tb_category(商品类目表，类目和商品(spu)是一对多关系，类目与品牌是多对多关系)】的数据库操作Service实现
* @createDate 2025-06-23 14:07:57
*/
@Service
public class TbCategoryServiceImpl extends ServiceImpl<TbCategoryMapper, TbCategory>
    implements TbCategoryService{
    @Autowired
   private TbCategoryMapper tbCategoryMapper;

    @Override
    public List<TbCategory> querryCategoryListByPrentId(Long pid) {
        QueryWrapper<TbCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",pid);
        List<TbCategory> categoryList = tbCategoryMapper.selectList(wrapper);
        return categoryList;
    }

    @Override
    public R saveCategory(TbCategory tbCategory) {
        tbCategoryMapper.insert(tbCategory);
        System.out.println("成功添加分类");
        return R.OK();
    }

    @Override
    public R updateCategory(Long id, String name) {

        QueryWrapper<TbCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);

        TbCategory tbCategory = tbCategoryMapper.selectOne(queryWrapper);
        tbCategory.setName(name);

        tbCategoryMapper.updateById(tbCategory);
        System.out.println("修改分类名称");
        return R.OK();
    }

    @Override
    public R delete(Long id) {

        TbCategory tbCategory = tbCategoryMapper.selectById(id);
        if (tbCategory.getIsParent()) {
            return R.ERROR(500, "该分类是父分类，无法删除");
        }

        int i = tbCategoryMapper.deleteById(id);
        if(i>0){
            return R.OK();
        }else {
            return R.ERROR(500, "该分类是父分类，无法删除");
        }




    }

    @Override
    public List<TbCategory> queryCategoryListByBrandId(Long bid) {
        return tbCategoryMapper.queryCategoryListByBrandId(bid);
    }

    @Override
    public List<String> queryNamesByIds(List<Long> list) {
        List<String> names = new ArrayList<>();
        list.forEach(id ->{
            TbCategory tbCategory = tbCategoryMapper.selectById(id);
            names.add(tbCategory.getName());
        });
        return names;
    }
}




